package com.ruoyi.industry.service.impl;

import java.util.*;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.industry.domain.SpaceIndustry;
import com.ruoyi.industry.mapper.DistrictMapper;
import com.ruoyi.industry.mapper.SpaceCollectMapper;
import com.ruoyi.industry.mapper.SpaceIndustryMapper;
import com.ruoyi.industry.utils.EntrustUtil;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.PathVo;
import com.ruoyi.system.api.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.industry.mapper.ProjectParkMapper;
import com.ruoyi.industry.domain.ProjectPark;
import com.ruoyi.industry.service.IProjectParkService;

import javax.servlet.http.HttpServletResponse;

/**
 * 项目-园区Service业务层处理
 *
 * @author MagicCube
 * @date 2023-05-05
 */
@Service
public class ProjectParkServiceImpl implements IProjectParkService
{
    private static final Logger log = LoggerFactory.getLogger(ProjectAuctionServiceImpl.class);

    @Autowired
    private ProjectParkMapper projectParkMapper;

    @Autowired
    private DistrictMapper districtMapper;

    @Autowired
    private SpaceIndustryMapper spaceIndustryMapper;

    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private SpaceCollectMapper spaceCollectMapper;
    /**
     * 查询项目-园区
     *
     * @param id 项目-园区主键
     * @return 项目-园区
     */
    @Override
    public ProjectPark selectProjectParkById(Long id)
    {
        return projectParkMapper.selectProjectParkById(id);
    }

    /**
     * 查询项目-园区列表
     *
     * @param projectPark 项目-园区
     * @return 项目-园区
     */
    @Override
    public List<ProjectPark> selectProjectParkList(ProjectPark projectPark)
    {
        List<Long> districtIds = new ArrayList<Long>();
        //城市
        if (projectPark.getCityId()!=null){
            districtIds.add(projectPark.getCityId());
            projectPark.setCityIds(districtIds);
        }else if (projectPark.getCityId()==null && projectPark.getProvinceId() != null){
            //查询省份下的城市
            districtIds.addAll(districtMapper.selectDistrictIdList(projectPark.getProvinceId()));
            districtIds.add(projectPark.getProvinceId());
            projectPark.setCityIds(districtIds);
        }
//        if (!SecurityUtils.getLoginUser().getRoles().contains("admin")){
//            projectPark.setSupplyUserId(SecurityUtils.getUserId());
//        }
        List<ProjectPark> projectParks = projectParkMapper.selectProjectParkListz(projectPark);
//        for (ProjectPark park : projectParks) {
//            SysUser sysUser = spaceIndustryMapper.selectSysUserById(park.getServicePhone());
//            if (sysUser!=null){
//                park.setContactName(sysUser.getNickName());
//                park.setContactPhone(sysUser.getPhonenumber());
//            }
//        }
        return projectParks;
    }

    /**
     * 新增项目-园区
     *
     * @param projectPark 项目-园区
     * @return 结果
     */
    @Override
    public int insertProjectPark(ProjectPark projectPark)
    {
        projectPark.setCreateTime(DateUtils.getNowDate());
        if (projectPark.getApprovalState() == null) {
//            if (SecurityUtils.getLoginUser().getRoles().contains("admin")) {
//                projectPark.setApprovalState(1L);//审核：通过
//            } else {
                projectPark.setApprovalState(0L);
//            }
        }
        projectPark.setSupplyUserId(SecurityUtils.getUserId());//发布人
        projectPark.setSerialNumber(IdUtils.fastSimpleUUID());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectPark, spaceIndustry);
        spaceIndustry.setCreateBy(SecurityUtils.getUsername());
        spaceIndustry.setCreateTime(projectPark.getCreateTime());
        spaceIndustry.setSpaceId(projectPark.getSerialNumber());
        spaceIndustry.setSupplyUserId(projectPark.getSupplyUserId());
        projectParkMapper.insertProjectPark(projectPark);
        spaceIndustry.setParkId(String.valueOf(projectPark.getId()));
        return spaceIndustryMapper.insertSpaceIndustry(spaceIndustry);
    }

    private static void extracted(ProjectPark projectPark, SpaceIndustry spaceIndustry) {
        spaceIndustry.setBuildType(1);
        spaceIndustry.setReleaseType(0L);//供给
        spaceIndustry.setApprovalState(projectPark.getApprovalState());
        spaceIndustry.setProvinceId(projectPark.getProvinceId());//省份
        spaceIndustry.setCityId(projectPark.getCityId());//城市
        spaceIndustry.setSupplyType(projectPark.getSupplyType());//服务类型
        spaceIndustry.setParkId(String.valueOf(projectPark.getId()));
        spaceIndustry.setHeating(projectPark.getParkHeating());//供暖
        spaceIndustry.setRefrig(projectPark.getParkRefrig());//制冷
        spaceIndustry.setPower(projectPark.getParkPower());//电力
        spaceIndustry.setGas(projectPark.getParkGas());//燃气
        spaceIndustry.setCoverResource(projectPark.getCoverResource());//封面资源
        spaceIndustry.setSpaceName(projectPark.getParkName());//园区名称
        spaceIndustry.setSpaceAllSize(projectPark.getParkAllSize());//空间总面积
        spaceIndustry.setTop(projectPark.getTop());//置顶
        spaceIndustry.setRecomState(projectPark.getRecomState());
    }

    /**
     * 修改项目-园区
     *
     * @param projectPark 项目-园区
     * @return 结果
     */
    @Override
    public int updateProjectPark(ProjectPark projectPark)
    {
        if (projectPark.getApprovalState() == null) {
            projectPark.setApprovalState(0L);
        }else if (projectPark.getId() != 0) {
            ProjectPark projectPark1 = projectParkMapper.selectProjectParkById(projectPark.getId());
            projectPark.setProvinceId(projectPark1.getProvinceId());
            projectPark.setCityId(projectPark1.getCityId());
            projectPark.setAreaId(projectPark1.getAreaId());
        }
        projectPark.setUpdateTime(DateUtils.getNowDate());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectPark,spaceIndustry);
        spaceIndustry.setSpaceId(String.valueOf(projectPark.getId()));
        spaceIndustry.setUpdateBy(SecurityUtils.getUsername());
        spaceIndustry.setUpdateTime(projectPark.getUpdateTime());
        spaceIndustryMapper.updateSpaceIndustryByParkId(spaceIndustry);
        return projectParkMapper.updateProjectPark(projectPark);
    }

    /**
     * 批量删除项目-园区
     *
     * @param ids 需要删除的项目-园区主键
     * @return 结果
     */
    @Override
    public int deleteProjectParkByIds(Long[] ids)
    {
        List<String> pathList = new ArrayList<>();
        for (ProjectPark projectPark : projectParkMapper.selectProjectParkByIds(ids)) {
            spaceIndustryMapper.deleteSpaceRecomById("园区",projectPark.getId());
            SpaceIndustryServiceImpl.deleteFile(
                    pathList,
                    projectPark.getVrResource(),
                    projectPark.getImgResource(),
                    projectPark.getCoverResource(),
                    projectPark.getVrcover(),
                    projectPark.getQrCode()
            );
        }
        spaceIndustryMapper.deleteSpaceIndustryByProjectParkIds(ids);
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        return projectParkMapper.deleteProjectParkByIds(ids);
    }

    /**
     * 删除项目-园区信息
     *
     * @param id 项目-园区主键
     * @return 结果
     */
    @Override
    public int deleteProjectParkById(Long id)
    {
        ProjectPark projectPark = projectParkMapper.selectProjectParkById(id);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectPark.getVrResource(),
                projectPark.getImgResource(),
                projectPark.getCoverResource(),
                projectPark.getVrcover(),
                projectPark.getQrCode()
        );
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceRecomById("园区",projectPark.getId());
        spaceIndustryMapper.deleteSpaceIndustryByProjectParkId(id);
        return projectParkMapper.deleteProjectParkById(id);
    }

    /**
     * 根据空间编号查询园区信息
     *
     * @param spaceId 空间编号
     * @param show
     * @return
     */
    @Override
    public Map<String, Object> selectProjectParkByNumber(String spaceId, boolean show) {
        ProjectPark projectPark = projectParkMapper.selectProjectParkByNumber(spaceId);
        if (SecurityUtils.getUserId()!=null&&SecurityUtils.getUserId()!=0) {
            if (show) {
                spaceIndustryMapper.updatePageViews(spaceId);
                projectParkMapper.updatePageViews(spaceId);
            }
            List<String> list = spaceCollectMapper.selectSpaceCollectByUserId(SecurityUtils.getUserId(), spaceId);
            if (list != null && list.size() != 0) {
                projectPark.setCollectState(1L);
            } else {
                projectPark.setCollectState(0L);
            }
        }else {
            projectPark.setCollectState(0L);
        }
        SysUser sysUser = spaceIndustryMapper.selectSysUserById(projectPark.getServicePhone());
        if (sysUser!=null){
            projectPark.setContactName(sysUser.getNickName());
            projectPark.setContactPhone(sysUser.getPhonenumber());
            projectPark.setQrCode(sysUser.getCodePic());
        }
        SpaceIndustry spaceIndustry = spaceIndustryMapper.selectSpaceIndustryBySpaceId(spaceId);
        if (spaceIndustry!=null){
            projectPark.setPageView(Long.valueOf(spaceIndustry.getPageViews()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("park",projectPark);
        map.put("space",projectPark);
        return map;
    }

    @Override
    public int deleteProjectParkBySerialNumber(String spaceId) {
        ProjectPark projectPark = projectParkMapper.selectProjectParkByNumber(spaceId);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectPark.getVrResource(),
                projectPark.getImgResource(),
                projectPark.getCoverResource(),
                projectPark.getVrcover(),
                projectPark.getQrCode()
        );
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceRecomById("园区",projectPark.getId());
//        spaceIndustryMapper.deleteSpaceIndustryBySerialNumber(spaceId);
//        return projectParkMapper.deleteProjectParkBySerialNumber(spaceId);
        spaceIndustryMapper.deleteSpaceIndustryByProjectParkId(projectPark.getId());
        return projectParkMapper.deleteProjectParkById(projectPark.getId());
    }

    private static final List<Long> STATE = Arrays.asList(0L,1L,2L,3L);

    @Override
    public String importUser(List<ProjectPark> projectParks, boolean updateSupport, String operName) {
        if (StringUtils.isNull(projectParks) || projectParks.size() ==0){
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Long count = 0L;

        for (ProjectPark projectPark : projectParks) {
            if (projectParks.indexOf(projectPark)==0&&projectPark.getParkName().equals("园区名称")) {
                continue;
            }
            count++;
            try {
                if (projectPark.getApprovalState()==null||STATE.contains(projectPark.getApprovalState())){
                    projectPark.setApprovalState(0L);
                }
                if (projectPark.getSupplyUserId()==null){
                    projectPark.setSupplyUserId(SecurityUtils.getUserId());
                }
                if (projectPark.getParkName()==null||projectPark.getParkName().equals("")){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + count + "条数据 缺少园区名称");
                    break;
                }
                projectPark.setCreateBy(SecurityUtils.getUsername());
                projectPark.setCreateTime(DateUtils.getNowDate());
                projectParkMapper.insertProjectPark(projectPark);
                successNum++;
                successMsg.append("<br/>" + successNum + "、园区 " + projectPark.getParkName() + " 导入成功");
            }catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、园区 " + projectPark.getParkName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void exportEntrust(HttpServletResponse response, Long id) {
        ProjectPark modal = projectParkMapper.selectProjectParkById(id);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("空间名称：" + modal.getParkName() + "<w:br/>");
        stringBuffer.append("产权方名称：" + modal.getParkBelong() + "<w:br/>");
        stringBuffer.append("产权方性质：" + modal.getParkNature() + "<w:br/>");
        stringBuffer.append("运营方名称：" + modal.getParkBusinName() + "<w:br/>");
        stringBuffer.append("运营方性质：" + modal.getParkBusinNature() + "<w:br/>");
        stringBuffer.append("运营方类型：" + modal.getParkBusinType() + "<w:br/>");
        stringBuffer.append("经济带：" + modal.getParkEconomic() + "<w:br/>");
        stringBuffer.append("区域位置：" + modal.getParkAreaAddress() + "<w:br/>");
        stringBuffer.append("园区类别：" + modal.getParkType() + "<w:br/>");
        stringBuffer.append("供给类型：" + modal.getSupplyType() + "<w:br/>");
        stringBuffer.append("园区竣工时间：" + modal.getParkFinish() + "<w:br/>");
        stringBuffer.append("产权年限：" + modal.getParkYears() + "<w:br/>");
        stringBuffer.append("剩余年限：" + modal.getParkSurplus() + "<w:br/>");
        stringBuffer.append("建筑结构：" + modal.getParkBuildStructure() + "<w:br/>");
        stringBuffer.append("总面积：" + modal.getParkAllSize() + "<w:br/>");
        stringBuffer.append("建筑面积：" + modal.getParkBuildSize() + "<w:br/>");
        stringBuffer.append("空置面积：" + modal.getParkFreeSize() + "<w:br/>");
        stringBuffer.append("容积率：" + modal.getParkPlotRatio() + "<w:br/>");
        stringBuffer.append("绿化率：" + modal.getParkGreen() + "<w:br/>");
        stringBuffer.append("园区产业定位：" + modal.getParkIndustry() + "<w:br/>");
        stringBuffer.append("供暖：" + modal.getParkHeating() + "<w:br/>");
        stringBuffer.append("制冷：" + modal.getParkRefrig() + "<w:br/>");
        stringBuffer.append("新风系统：" + modal.getParkNather() + "<w:br/>");
        stringBuffer.append("电量：" + modal.getParkPower() + "<w:br/>");
        stringBuffer.append("燃气：" + modal.getParkGas() + "<w:br/>");
        stringBuffer.append("水：" + modal.getParkWater() + "<w:br/>");
        stringBuffer.append("商圈：" + modal.getParkDistrict() + "<w:br/>");
        stringBuffer.append("智慧园区程度：" + modal.getParkWisdom() + "<w:br/>");
        stringBuffer.append("园区车位：" + modal.getParkCarlot() + "<w:br/>");
        stringBuffer.append("专用物流通道：" + modal.getParkLogistics() + "<w:br/>");
        stringBuffer.append("园区保安：" + modal.getParkSecurity() + "<w:br/>");
        stringBuffer.append("园区环保要求：" + modal.getParkPolluteAsk() + "<w:br/>");
        stringBuffer.append("公交：" + modal.getParkBus() + "<w:br/>");
        stringBuffer.append("地铁：" + modal.getParkMetro() + "<w:br/>");
        stringBuffer.append("高速公路：" + modal.getParkHighRoad() + "<w:br/>");
        stringBuffer.append("火车站：" + modal.getParkTrainStation() + "<w:br/>");
        stringBuffer.append("机场：" + modal.getParkAirport() + "<w:br/>");
        stringBuffer.append("港口：" + modal.getParkPort() + "<w:br/>");
        stringBuffer.append("周边商务酒店：" + modal.getParkHotel() + "<w:br/>");
        stringBuffer.append("周边配套学校：" + modal.getParkSchool() + "<w:br/>");
        stringBuffer.append("园区餐饮：" + modal.getParkRestaurant() + "<w:br/>");
        stringBuffer.append("园区配套班车：" + modal.getParkShuttleBus() + "<w:br/>");
        stringBuffer.append("园区周边场馆：" + modal.getParkRecreation() + "<w:br/>");
        stringBuffer.append("众创空间：" + modal.getParkShareSpace() + "<w:br/>");
//        stringBuffer.append("园区政策：" + modal.getParkLandPolic() + "<w:br/>");
        stringBuffer.append("产业孵化平台：" + modal.getParkPlatform() + "<w:br/>");
        stringBuffer.append("服务平台及科研平台：" + modal.getParkScience() + "<w:br/>");
        stringBuffer.append("注册或办公地址：" + modal.getParkAddress() + "<w:br/>");
        stringBuffer.append("区域：" + modal.getParkArea() + "<w:br/>");
        stringBuffer.append("区域情况介绍：" + modal.getParkAreaIntro() + "<w:br/>");
        stringBuffer.append("经度：" + modal.getParkLongitude() + "<w:br/>");
        stringBuffer.append("纬度：" + modal.getParkLatitude() + "<w:br/>");
        stringBuffer.append("联系人：" + modal.getContactName() + "<w:br/>");
        stringBuffer.append("联系方式：" + modal.getContactPhone() + "<w:br/>");
        new EntrustUtil().exportWord(stringBuffer,response);
    }
}
